<template>
  <Dialog v-model="dialogVisible" :title="title" width="80%" :minHeight="900">
    <ExcelParser
      :tips="tips"
      ref="excelParserRef"
      :importApi="TeacherApi.importTeacher"
      :targetTableColumns="importColumns"
      :templateName="title"
    />
    <template #footer>
      <el-button type="primary" @click="onBatchImport()" :loading="importLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts" name="ImportTeacherDialog">
import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
import * as TeacherApi from '@/api/cmis/teacher'
import { ITargetTableColumbnItem } from '@/components/ExcelParser/src/type'
import { DICT_TYPE, getDictValuesStr } from '@/utils/dict'

const importLoading = ref(false)
const excelParserRef = ref()

const title = ref('导入老师')
const dialogVisible = ref(false)
const tips = ref([
  '机构名称: 可以是学校名称等',
  '性别编码: ' + getDictValuesStr(DICT_TYPE.SYSTEM_USER_SEX)
])
const importColumns = ref<ITargetTableColumbnItem[]>([
  {
    label: '老师编码',
    field: 'teacherCode',
    rules: [required('老师编码不能为空')]
  },
  {
    label: '姓名',
    field: 'teacherName',
    rules: [required('姓名不能为空')]
  },
  {
    label: '身份证号',
    field: 'idNumber',
    rules: []
  },
  {
    label: '性别编码',
    field: 'sex',
    rules: [required('性别不能为空')],
    parseRule: {
      dictType: DICT_TYPE.SYSTEM_USER_SEX,
      defaultValue: 3
    }
  },
  {
    label: '班级名称',
    field: 'classesName',
    rules: []
  },
  {
    label: '专业名称',
    field: 'majorName',
    rules: []
  },
  {
    label: '机构名称',
    field: 'collegeName',
    rules: []
  },
  {
    label: '学校名称',
    field: 'schoolName',
    rules: [required('学校不能为空')]
  },
  {
    label: '手机号码',
    field: 'mobile',
    rules: []
  },
  {
    label: '口令',
    field: 'openId',
    rules: []
  }
])

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const onBatchImport = async () => {
  importLoading.value = true
  const isSuccess = await excelParserRef.value.onSubmit()
  if (isSuccess) {
    importLoading.value = false
    ElMessage({
      message: '导入成功',
      type: 'success',
      duration: 1000,
      onClose: () => {
        // importLoading.value = false
        dialogVisible.value = false
      }
    })
    emit('success')
  } else {
    importLoading.value = false
    return
  }
  importLoading.value = false
  dialogVisible.value = false
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  console.log('open')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
